package com.helloUIBinder.client.customComponents;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Node;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.helloUIBinder.client.events.OnEditDeleteCellClickEvent;

public class EditDeleteCell extends AbstractCell<String> {

    private SimpleEventBus eventBus;

    public EditDeleteCell(SimpleEventBus eventBus) {

        super("click", "keydown");
        this.eventBus = eventBus;
    }

    @Override
    public void render(Context context, String value, SafeHtmlBuilder sb) {


        /*
        * Always do a null check on the value. Cell widgets can pass null to
        * cells if the underlying data contains a null, or if the data arrives
        * out of order.
        */
        if (value == null) {
            return;
        }

        sb.appendHtmlConstant("<div><span><img src =\"img/edit.png\"/></span><span>&nbsp;&nbsp;&nbsp;</span><span><img src =\"img/delete.png\"/></span></div>");
    }

    @Override
    public void onBrowserEvent(Context context, Element parent, String value, NativeEvent event, ValueUpdater<String> valueUpdater) {

        // Let AbstractCell handle the keydown event.
        super.onBrowserEvent(context, parent, value, event, valueUpdater);

        // Handle the click event.
        if ("click".equals(event.getType())) {
            // Ignore clicks that occur outside of the outermost element.
            EventTarget eventTarget = event.getEventTarget();
            Node first = parent.getChild(0);//get parrent div

            Node editSpan = first.getChild(0);//get first span with img
            Node deleteSpan = first.getChild(2);//get second span with img;

            if (editSpan.isOrHasChild(Element.as(eventTarget))) {
                OnEditDeleteCellClickEvent clickEvent = new OnEditDeleteCellClickEvent();
                clickEvent.setClickedButton(OnEditDeleteCellClickEvent.EDIT);
                clickEvent.setClickedId(Integer.parseInt(value));
                eventBus.fireEvent(clickEvent);
            }
            if (deleteSpan.isOrHasChild(Element.as(eventTarget))) {
                OnEditDeleteCellClickEvent clickEvent = new OnEditDeleteCellClickEvent();
                clickEvent.setClickedButton(OnEditDeleteCellClickEvent.DELETE);
                clickEvent.setClickedId(Integer.parseInt(value));
                eventBus.fireEvent(clickEvent);
            }
        }
    }
}